package com.servlet;

import com.bean.*;
import com.dao.BhSyCaseDao;
import com.dao.BhtopicDao;
import com.dao.impl.BhSyCaseDaoImpl;
import com.dao.impl.BhtopicDaoImpl;
import com.google.gson.Gson;
import com.util.Generate;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;
import org.apache.poi.ss.usermodel.Row;
import org.junit.Test;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.*;
import java.sql.SQLException;
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

@WebServlet("/BhSyDao/Teacher/*")
public class BhSyCaseAllDaoServlet extends BaseServlet{
    SimpleDateFormat simp  = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    BhSyCaseDao bcd = new BhSyCaseDaoImpl();
    BhtopicDao bti = new BhtopicDaoImpl();
    List<Bhtopic> bhTopList = new ArrayList<>();
    Bhcase bc = null;
    //----------------------------试卷编辑-----------------------
    public void upCaseMes(HttpServletRequest request,HttpServletResponse response){
        try {

            HttpSession session = request.getSession();
            request.setCharacterEncoding("utf-8");
            //清空题目集合
            bc = null;
            bhTopList.clear();
            //获取用户信息
            BhUser bu = (BhUser) session.getAttribute("BhSyUser");
            //获取试卷信息
            String cName = request.getParameter("cName");//试卷名称
            String cFlag = request.getParameter("flag");//试卷是否在考完试后公布答案
            String beginTime = request.getParameter("beginTime");//考试开始时间
            String endTime = request.getParameter("endTime");//考试结束时间

            Date beg = simp.parse(beginTime);
            Date end = simp.parse(endTime);
            boolean flag = false;
            if (cFlag.equals("是")){
                flag = true;
            }else {
                flag = false;
            }
            bc = new Bhcase(bu.getuID(),null,cName,flag,beg,end);
            request.getRequestDispatcher("/WEB-INF/jsp/UpLoadCaseTopic.jsp").forward(request,response);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (ParseException e) {
            e.printStackTrace();
        } catch (ServletException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }

    }



    //-------------------老师通过Excel上传试卷题目----------------------
    public void upLoadExcel(HttpServletRequest request, HttpServletResponse response){
        HttpSession session = request.getSession();
        BhUser bu = (BhUser) session.getAttribute("BhSyUser");
        DiskFileItemFactory dff = new DiskFileItemFactory();//配置上传参数
        ServletFileUpload sfu = new ServletFileUpload(dff);
        sfu.setHeaderEncoding("UTF-8");//中文处理
        //项目的发布位置
        String apppath = request.getServletContext().getRealPath("/file");
        System.out.printf("上传位置="+apppath);
        String isSameTop = null;
        try {
            List<FileItem> list = sfu.parseRequest(request);
            //存盘 d:/xxxx/xxx/file
            for (FileItem fi:list) {
                if (fi.isFormField()){
                    continue;
                }else {
                    //文件
                    File file = new File(apppath+"/"+fi.getName());
                    fi.write(file);
                    getExcelMes(apppath+"/"+fi.getName(),bu.getuID());
                }
            }
                session.setAttribute("flagUlCase",1);
                session.setAttribute("bhTopList",bhTopList);
                request.getRequestDispatcher("/WEB-INF/jsp/UpLoadCaseTopic.jsp").forward(request,response);
        } catch (FileUploadException e) {
            e.printStackTrace();
        } catch (Exception e) {
            e.printStackTrace();
        }

    }
    //-------------------------------------判断题目是否存在,并且丛Excel后读取数据,在数据库中进行数据处理添加---------------------------
    public void getExcelMes(String appPath,int uid){
        boolean flag = false;
        List<Bhtopic> listBh = new ArrayList<>();
        Bhtopic bt = null;
        File f = new File(appPath);
        try {
            InputStream input = new FileInputStream(f);
            HSSFWorkbook sheets = new HSSFWorkbook(input);
            //XSSFSheet sheet = sheets.getSheet("Sheet1");  // 根据标签去第几个表格
            HSSFSheet sheet = sheets.getSheetAt(0);
            //获取行数
            int rows = sheet.getPhysicalNumberOfRows();
            HSSFRow row = sheet.getRow(0);
            int cols = row.getPhysicalNumberOfCells();
            System.out.println("文件多少行" + rows);
            System.out.println("文件多少列" + cols);
            List<String> list = null;
            for (int i = 1; i < rows; i++) {
                list = new ArrayList();
                Row r = sheet.getRow(i);
                for (int j = 0; j < cols; j++) {
                    if (r.getCell(j) == null) {
                        continue;
                    } else {
                        list.add(String.valueOf(r.getCell(j)));
                    }
                }
                bt = new Bhtopic();
                bt.setuID(uid);
                for (int j = 0; j < list.size(); j++) {
                    if (j == 0) {
                        bt.setcType(list.get(j));
                    } else if (j == 1) {
                        bt.setcPor(list.get(j));
                    } else if (j == 2) {
                        bt.setcTrue(list.get(j));
                    } else if (j == 3) {
                        bt.setcA(list.get(j));
                    } else if (j == 4) {
                        bt.setcB(list.get(j));
                    } else if (j == 5) {
                        bt.setcC(list.get(j));
                    } else if (j == 6) {
                        bt.setcD(list.get(j));
                    } else if (j == 7) {
                        bt.setcNum(Integer.parseInt(list.get(j)));
                    }
                    listBh.add(bt);
                }

                bcd.bhInertExcelTopic(listBh, uid);
            }
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    @Test
    public void removeArry(){
        BhtopicDao bd = new BhtopicDaoImpl();
        try {
            List<Bhtopic> list = bd.selectBhtopic("默认题库",2);
            System.out.println("--------------------------------");
            list.remove(2);
            System.out.println(list);
            System.out.println(list.size());
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    //---------------------------------------Ajax删除选中的题目----------------------------
    public void ajaxDelTopic(HttpServletRequest request, HttpServletResponse response){
        try {
            request.setCharacterEncoding("utf-8");
            response.setCharacterEncoding("utf-8");
            response.setContentType("text/html");
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        }

        String uTopic =  request.getParameter("uTopic");
        System.out.println(uTopic);
        String[] uTopicArry = uTopic.split("/");
        for (int i = 0; i < uTopicArry.length ; i++) {
            for (int j = 0; j < bhTopList.size() ; j++) {
                if (bhTopList.get(j).getcPor().replaceAll("\r|\n", "").equals(uTopicArry[i])){
                    System.out.println("1");
                    bhTopList.remove(j);
                    break;
                }else {
                    continue;
                }
            }
        }
        System.out.println("-----------------------------------");
        Gson g = new Gson();
        String json = g.toJson(bhTopList);
        System.out.println(json);
        try {
            PrintWriter pw = response.getWriter();
            pw.print(json);
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
    //----------------------ajax查询题库----------------
    public void ajaxSelTioIcKu(HttpServletRequest request, HttpServletResponse response){
        try {
            HttpSession session = request.getSession();
            BhUser bu = (BhUser) session.getAttribute("BhSyUser");
            request.setCharacterEncoding("utf-8");
            response.setCharacterEncoding("utf-8");
            response.setContentType("text/html");
            List<UserTopicKu> list = bcd.bhSelUserTK(bu.getuID());
            Gson g = new Gson();
            String json = g.toJson(list);
            PrintWriter pw = response.getWriter();
            pw.print(json);
        } catch (Exception e){
            e.printStackTrace();
        }
    }
    //-------------------------查询ajax库中的题库--------------------------
    public void ajaxSelTopIc(HttpServletRequest request,HttpServletResponse response){
        try {
            HttpSession session = request.getSession();
            BhUser bu = (BhUser) session.getAttribute("BhSyUser");
            request.setCharacterEncoding("utf-8");
            response.setCharacterEncoding("utf-8");
            response.setContentType("text/html");
            String tName = request.getParameter("tName");
            List<Bhtopic> list = bti.selectBhtopic(tName,bu.getuID());
            Gson gs = new Gson();
            String json = gs.toJson(list);
            PrintWriter pw = response.getWriter();
            pw.print(json);
        }catch (Exception e){
            e.printStackTrace();
        }
    }
    //-------------------------------------将题库题目返回到前端-------------------------------
    public void ajaxTheTopicKuAddTopic(HttpServletRequest request,HttpServletResponse response){
        HttpSession session = request.getSession();
        try {
            BhUser bu = (BhUser) session.getAttribute("BhSyUser");
            request.setCharacterEncoding("utf-8");
            response.setCharacterEncoding("utf-8");
            response.setContentType("text/html");
            String uTopic = request.getParameter("uTopic");
            System.out.println(uTopic);
            String[] topIc = uTopic.split("/");
            //分割完了准备进行查询
            List<Bhtopic> listBhT = bcd.getBhTopicForPor(bu.getuID(),topIc);
            System.out.println("-------------------------");
            System.out.println(listBhT);

            boolean flag = false;
            System.out.println(bhTopList.size());
            if (bhTopList.size()<=0){
                for (int i = 0; i < listBhT.size() ; i++) {
                    bhTopList.add(listBhT.get(i));
                }
            }else {
                for (int i = 0; i < listBhT.size() ; i++) {
                    for (int j = 0; j < bhTopList.size() ; j++) {
                        if (listBhT.get(i).getcPor().equals(bhTopList.get(j).getcPor())){
                            flag = true;
                            break;
                        }else {
                            flag = false;
                        }
                    }
                    if (flag==false){
                        bhTopList.add(listBhT.get(i));
                    }
                }
            }
            System.out.println("---------------------------");
            System.out.println(bhTopList);
            Gson gs = new Gson();
            String json = gs.toJson(bhTopList);
            PrintWriter pw = response.getWriter();
            pw.print(json);
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
    //--------------------------------发布试卷-------------------------------------
    public void pushTheCase(HttpServletRequest request, HttpServletResponse response){
        try {
            System.out.println("-----------------------------------------");
            request.setCharacterEncoding("utf-8");
            HttpSession session = request.getSession();
            //获取多个input值
            String[] cNum =(String[]) request.getParameterValues("caseNum");
            String az= Generate.shen();
            System.out.println("考试网址----"+az);
            //将生成的考试网址添加到试卷信息上
            bc.setcUrl(az);
            System.out.println("试卷信息----"+bc);
            String caseNum ="";
            String caseTId ="";
            List<Bhtopic> listBt = bcd.selBhTopicForProAType(bhTopList);
            for (int i = 0; i < cNum.length ; i++) {
                if (i==0){
                    caseNum+=cNum[i];
                    caseTId+=listBt.get(i).getTopIcID();
                    continue;
                }
                caseNum+=","+cNum[i];
                caseTId+=","+listBt.get(i).getTopIcID();
            }
            System.out.println(caseNum);
            System.out.println(caseTId);
            Bhcasetm btm = new Bhcasetm(az,caseNum,caseTId);
            System.out.println(btm);
            //将试卷数据添加到数据库中
            bcd.addBhTopIcTm(btm);
            bcd.addBhCase(bc);
            //清空所有全局变量
            bhTopList.clear();
            bc=null;
            request.setAttribute("urlAz",az);
            request.getRequestDispatcher("/WEB-INF/js/UpLoadWc.jsp").forward(request,response);
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (SQLException throwables) {
            throwables.printStackTrace();
        } catch (ServletException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
